package com.mytest.provider.service.controller;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.myrest.provider.poi.work.entities.user.NickName;
import com.myrest.provider.poi.work.entities.user.Sex;
import com.myrest.provider.poi.work.entities.user.SysUser;
import com.myrest.provider.poi.work.entities.user.nickAndSex;
import com.mytest.common.result.Result;
import com.mytest.common.result.ResultGenerator;
import com.mytest.provider.service.service.NickAndSexService;
import com.mytest.provider.service.service.NickNameService;
import com.mytest.provider.service.service.SexService;
import com.mytest.provider.service.service.SysUserService;
import com.rabbitmq.client.AMQP;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Lists;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Author: llq
 * @Date: 2020/4/1
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class SysUserController {

    @Autowired
    SysUserService sysUserService;

    @Autowired
    NickNameService nickNameService;

    @Autowired
    SexService sexService;

    @Autowired
    NickAndSexService nickAndSexService;

    @Autowired
    AmqpTemplate amqpTemplate;

    @GetMapping("/selectAll")
    public List<SysUser> selectUserAll(@RequestParam Map<String,Object> param){
//        SysUser sysUser = sysUserService.selectById(1);
        List<SysUser> users = sysUserService.selectList(new EntityWrapper<SysUser>().eq("del_flag", 0));
        System.out.println("你好啊");
        return users;
    }

    /**
     * 昵称id获取昵称类
     * @param param
     * @return
     */
    @GetMapping("/selectNick")
    public NickName selectNick(@RequestParam Map<String,Object> param){
        Long id = MapUtil.getLong(param, "id");
        NickName nickName = nickNameService.selectById(id);
        return nickName;
    }

    /**
     * 根据id获取性别名字
     * @param lds
     * @return
     */
    @GetMapping("/selectSexByIds")
    public List<Integer> selectSexByIds(@RequestParam List<Long> lds){
        List<Sex> sexes = sexService.selectBatchIds(lds);
        List<Integer> names = Lists.newArrayList();
        sexes.forEach(sex -> {
            names.add(sex.getSex());
        });
        return names;
    }

    /**
     * 根据性别id获取nickAndSex集合
     * @param id
     * @return
     */
    @GetMapping("/selectNickAndSexBySexId")
    public List<nickAndSex> selectNickAndSexBySexId(@RequestParam Long id){
        List<nickAndSex> nickAndSexs = nickAndSexService.selectList(new EntityWrapper<nickAndSex>().eq("sexid", id));
        return nickAndSexs;
    }

    @GetMapping("/select")
    public SysUser selectUser(@RequestParam Map<String,Object> param){
        SysUser sysUser = sysUserService.selectById(1);
        return sysUser;
    }

    @PostMapping("/insert")
    public SysUser insertUser(@RequestParam Map<String,Object> param){
        SysUser sysUser = new SysUser();
        sysUser.setUsername("ss");
        sysUser.setNickName("S");
        sysUser.setDelFlag(0);
        sysUser.setPassword("123");
        sysUser.setSex(1);
        sysUser.setStatus(1);

        /*sysUserService.insert(sysUser);

        SysUser sysUser1 = sysUserService.selectById(2);*/
        SysUser sysUser1 = sysUserService.selectById(1);
        return sysUser1;
    }

    @GetMapping("/mq")
    public SysUser selectMq(@RequestParam Map<String,Object> param){

        System.out.println("111");
        SysUser sysUser = sysUserService.selectById(1);
        String nickName = sysUser.getNickName();
        this.sendMessage(nickName,"zzz");
        return sysUser;
    }

    /**
     * @param nickName
     * @param type
     */
    private void sendMessage(String nickName, String type){
        // 发送消息
        try {
            System.out.println("111");
            this.amqpTemplate.convertAndSend("mytest.item.exchange","mmm." + type, 4);

            System.out.println("222");
        } catch (Exception e) {
            log.error("消息异常", type, nickName, e);
        }
    }

    @GetMapping("/send")
    public String send() {
        //消息
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("email", "xx@163.com");
        jsonObject.put("timestamp", 0);
        String jsonString = jsonObject.toJSONString();
        System.out.println("jsonString:" + jsonString);

        // 设置消息唯一id 保证每次重试消息id唯一
        Message message = MessageBuilder.withBody(jsonString.getBytes())
                .setContentType(MessageProperties.CONTENT_TYPE_JSON).setContentEncoding("utf-8")
                //消息id设置在请求头里面 用UUID做全局ID
                .setMessageId(UUID.randomUUID() + "").build();

//        amqpTemplate.convertAndSend(queueName, message);  没用
//        this.amqpTemplate.convertAndSend("fanoutExchange", message);  没用

//        amqpTemplate.convertAndSend("fanoutExchange", "email.x", message);  正常发送消息


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("消息发送时间:"+sdf.format(new Date()));
        // 发送延迟消息 （即设置定时时间）
        amqpTemplate.convertAndSend("delayedExchange", "email.x", message,mes -> {
            mes.getMessageProperties().setHeader("x-delay",20000);
            return mes;});

        //rabbitTemplate延迟
        /*rabbitTemplate.convertAndSend("test_exchange", queueName, msg, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setHeader("x-delay",3000);
                return message;
            }
        });*/

        // 设置队列中消息的存活时间（时间一到，还没有服务接收消息，就不能在接收消息了，当然如果绑定了死信交换机的话，就会转到死信队列），不是定时时间
        /*amqpTemplate.convertAndSend("delayedExchange", "email.x", message,mes -> {
            mes.getMessageProperties().setExpiration("20000";
            return mes;});*/


        /*amqpTemplate.convertAndSend("dead_exchange", "dead_routing_key", message,mes -> {
            mes.getMessageProperties().setExpiration("20000");
            return mes;});*/

        return "11";
    }




    @GetMapping("/id/{uid}/{name}")
    public ResponseEntity<SysUser> finduserbyid(@PathVariable("uid")Integer uid,@PathVariable("name")String name) {
        try {
            if (uid == null || uid <= 0) {
                // 参数列表不合法400
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
            }
            SysUser user = sysUserService.selectById(uid);
            if (user == null) {
                // 没有返回值404
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }
                //  get请求得到返回值200
                //  return ResponseEntity.status(HttpStatus.OK).body(user);下面是简写
            return ResponseEntity.ok(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
                //  服务器类部错误500
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }

    @GetMapping("/pageList")
    public Result pageList(@RequestParam Map<String, Object> param, HttpServletResponse response) {

        Map<String, Object> map = sysUserService.selectMap(new EntityWrapper<SysUser>().eq("id", 2));
        return ResultGenerator.genSuccessResult(map);
//        ResponseUtil.out(response, map);
    }
}
